﻿using System;
using System.Collections.Generic;
using Melee.Controller.Handlers;
using Melee.Controller.Storage;
using Newtonsoft.Json;

namespace Melee.Controller.Comet
{
    class Listener
    {
        private const string MESSAGE_FORMAT = "\"[{0}]{1}:{2}\"";
        private DateTime m_lastCometTime = DateTime.Now;
        private IList<Message> m_messages = new List<Message>();
        private string m_userName = null;

        private Guid m_LoginId = Guid.Empty;
        public Guid LoginId { get { return m_LoginId; } }

        private AsyncResult m_AsyncResult = null;
        public AsyncResult AsyncResult
        {
            set
            {
                m_lastCometTime = DateTime.Now;
                m_AsyncResult = value;

                if (0 < m_messages.Count)
                    Response();
            }
        }

        public bool IsInvalid { get { return 2 < (DateTime.Now - m_lastCometTime).TotalMinutes; } }

        public bool IsConnectedToolong { get { return 10 < (DateTime.Now - m_lastCometTime).TotalSeconds; } }

        public Listener(Guid loginId, string userName)
        {
            m_LoginId = loginId;
            m_userName = userName;
        }

        public void Listen(Message message, string to)
        {
            bool isSystemMessageForMe = MessageType.System == message.Type && (null == to || m_userName == to);
            bool isWhisperMessageForMe = MessageType.Whisper == message.Type &&
                (message.From != to && (message.From == m_userName || to == m_userName));
            if (MessageType.Generial == message.Type || isSystemMessageForMe || isWhisperMessageForMe)
                m_messages.Add(message);

            if (null != m_AsyncResult)
                Response();
        }

        private void Response()
        {
            string script = string.Format("require(\"chat\").AddMessage({0});", JsonConvert.SerializeObject(m_messages));

            IHttpStorage storage = HttpStorageFactory.GetStorage(m_AsyncResult.Context);
            storage.Add(HttpStorageKeys.Success, true);
            storage.Add(HttpStorageKeys.Data, script);

            m_messages.Clear();
            m_AsyncResult.SetCompleted();
            m_AsyncResult = null;
        }

        public void Disconnected()
        {
            if (null == m_AsyncResult) return;

            IHttpStorage storage = HttpStorageFactory.GetStorage(m_AsyncResult.Context);
            storage.Add(HttpStorageKeys.Success, false);
            m_AsyncResult.SetCompleted();
            m_AsyncResult = null;
        }
    }
}
